<?php
namespace app\admin\traits;

use think\facade\Db;

trait Column{
    /**
     * @title 获取枚举类型字段的选项值
     * @param string $type
     * @return array
     * @author FashionJune
     */
    public function getEnumList(string $type = 'array')
    {
        $prefix = config('database.connections.mysql.prefix');
        $field_list = Db::cache(30)->query("show full columns from {$prefix}{$this->name}");
        $enum_list = [];
        foreach ($field_list as $field) {
            if (substr($field['type'], 0, 4) === 'enum') {
                $str = substr($field['type'], 5, -1);
                $enum = explode(',', str_replace('\'', '', $str));
                if ($type == 'object') {
                    $obj = [];
                    foreach ($enum as $v) {
                        $obj[] = ['label' => $v];
                    }
                    $enum = $obj;
                }
                $enum_list[$field['field']] = $enum;
            }
        }
        return $enum_list;
    }
}